<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" @keyup.enter.native="handleQuery">
          <el-option label="未绑定" value="0"></el-option>
          <el-option label="绑定" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:codeid:add']">创建号段</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="setActiveReward">设置激活奖励</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="codeidList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column label="号段ID" align="center" prop="id" />
      <el-table-column label="号段" align="center" prop="numberSection" />
      <el-table-column label="状态" align="center" prop="state" >
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0"> 未绑定 </span>
          <span v-if="scope.row.state == 1"> 绑定 </span>
        </template>
      </el-table-column>
      <el-table-column label="绑定商户" align="center" prop="nickName" />
      <el-table-column label="编码数量" align="center" prop="quantity" />
      <el-table-column label="已使用数量" align="center" prop="quantityUsed" />
      <el-table-column label="生成时间" align="center" prop="creationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleCreate(scope.row)"
          >生成编码</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleBind(scope.row)"
          >绑定商户</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改识别码对话框 -->
    <el-dialog title="生成编码" :visible.sync="createCodeOpen" width="600px" append-to-body>
      <div style="display: flex;align-items: center;justify-content: flex-start;">
        <div style="margin-right: 24px;height: 32px;line-height: 32px;">
          号段：{{detail.numberSection}}
        </div>
        <div style="margin-right: 24px">
          生成数量：<el-input v-model="quantity" style="width: 200px" placeholder="请输入" size="small"></el-input>
        </div>
        <div>
          <el-button type="primary" @click="handleCreateCode" size="small">确定生成</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="绑定商户" :visible.sync="bindOpen" width="600px" append-to-body>
      <div style="display: flex;align-items: center;justify-content: flex-start;">
        <div style="margin-right: 24px">
          商户名称：
          <el-select
            style="width: 200px"
            v-model="merchantName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入名称搜索"
            :remote-method="remoteMethod"
          @change="merchantChange">
            <el-option
              v-for="item in merchantList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div style="margin-right: 24px">
          <el-button size="small"  type="primary" @click="searchBindMerchant">搜索</el-button>
        </div>
        <div>
          <el-button type="primary" @click="handleBindMerchant" size="small">保存</el-button>
        </div>
      </div>
      <div v-if="merchantInfo && merchantInfo.phonenumber" style="margin-top: 12px">手机号码：{{merchantInfo.phonenumber}}</div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="号段" prop="numberSection">
          <el-input v-model="form.numberSection" placeholder="请输入号段" />
        </el-form-item>
        <el-form-item label="编码数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置激活奖励" :visible.sync="openRewardAmount" width="500px" append-to-body>
      <div style="padding: 0 40px">
        <div>当前奖励金额：￥{{rewardAmount}}</div>
        <div style="margin-top: 12px">修改为：<el-input v-model="newRewardAmount" placeholder="请输入金额" style="width: 300px" /> </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRewardAmount">确 定</el-button>
        <el-button type="" @click="cancelRewardAmount">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCodeid,
  getCodeid,
  delCodeid,
  addCodeid,
  updateCodeid,
  createCodeId,
  getMerchantList, saveMerchant, getRewardAmount, editRewardAmount
} from "@/api/system/codeid";

export default {
  name: "Codeid",
  components: {},
  data() {
    return {
      openRewardAmount:false,
      rewardAmount:0,
      newRewardAmount:'',
      merchantList:[],
      merchantInfo:undefined,
      detail: {},
      merchantName:undefined,
      createCodeOpen:false,
      bindOpen:false,
      quantity:undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 识别码表格数据
      codeidList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        numberSection: null,
        state: null,
        userId: null,
        quantity: null,
        quantityUsed: null,
        creationTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitRewardAmount(){
      //校验newRewardAmount字段为金额
      if(!/^(([1-9]\d*)|0)(\.\d{1,2})?$/.test(this.newRewardAmount)){
        this.$message({
          type: 'warning',
          message: '请输入正确的金额'
        });
        return;
      }
      editRewardAmount({rewardAmount:this.newRewardAmount}).then(res=>{
        this.openRewardAmount = false;
        this.newRewardAmount = '';
        this.rewardAmount = 0;
        this.$message({
          type: 'success',
          message: '设置成功'
        });
      })
    },
    cancelRewardAmount(){
      this.openRewardAmount = false;
      this.newRewardAmount = '';
      this.rewardAmount = 0;
    },
    merchantChange(data){
      if(data == ''){
        this.merchantInfo = {};
      }else{
        this.merchantInfo = this.merchantList.find(item => item.id == data);
      }
    },
    remoteMethod(query) {
      getMerchantList({nickName:query}).then(response => {
        const data = response.data;
        this.merchantList = data;
      });
    },
    handleCreateCode(){
      createCodeId({
        quantity:this.quantity,
        id:this.detail.id,
        numberSection:this.detail.numberSection
      }).then(response => {
        this.createCodeOpen = false;
        this.quantity = undefined;
        this.getList();
      });
    },
    handleCreate(row){
      this.detail = row;
      this.createCodeOpen = true;
      this.quantity = undefined;
    },
    handleDetail(row){
      this.detail = row;
      this.$router.push({ name: "CodeidDetail", params:{ id: row.id }});
    },
    handleBind(row){
      this.detail = row;
      this.bindOpen = true;
      this.merchantInfo = undefined
      this.merchantName = undefined;
    },
    searchBindMerchant(){

    },
    handleBindMerchant(){
      if(!this.merchantInfo){
        this.$message.warning('请选择商户');
        return
      }
      saveMerchant({
        id:this.detail.id,
        userId:this.merchantInfo.id
      }).then(res=>{
        this.bindOpen = false;
        this.$message.success('绑定成功');
        this.getList();
      })
    },
    /** 查询识别码列表 */
    getList() {
      this.loading = true;
      listCodeid(this.queryParams).then(response => {
        this.codeidList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        numberSection: null,
        quantity: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    setActiveReward(){
      getRewardAmount().then(res=>{
        this.rewardAmount = res.data.rewardAmount
        this.openRewardAmount = true
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加识别码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCodeid(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改识别码";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCodeid(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCodeid(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除识别码编号为"' + ids + '"的数据项？').then(function() {
        return delCodeid(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/codeid/export', {
        ...this.queryParams
      }, `codeid_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
